package main

import (
	"log"
	"os"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"

	"plastic-company/internal/config"
	"plastic-company/internal/handler"
	"plastic-company/internal/middleware"
	"plastic-company/internal/model"
)

func main() {
	// 加载环境变量
	if err := godotenv.Load(); err != nil {
		log.Fatal("Error loading .env file")
	}

	// 初始化数据库
	db, err := gorm.Open(mysql.Open(config.GetDSN()), &gorm.Config{})
	if err != nil {
		log.Fatal("Failed to connect to database")
	}

	// 自动迁移数据库
	db.AutoMigrate(
		&model.Admin{},
		&model.Product{},
		&model.Application{},
		&model.News{},
		&model.Contact{},
	)

	// 设置handler包中的数据库连接
	handler.SetDB(db)

	// 设置路由
	r := gin.Default()

	// 添加CORS中间件
	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	// API路由组
	api := r.Group("/api/v1")
	{
		// 认证路由
		auth := api.Group("/auth")
		{
			auth.POST("/register", handler.Register)
			auth.POST("/login", handler.Login)
			auth.POST("/logout", middleware.RequireAuth(), handler.Logout)
			auth.GET("/me", middleware.RequireAuth(), handler.Me)
		}

		// 产品路由
		products := api.Group("/products")
		products.Use(middleware.RequireAuth())
		{
			products.GET("", handler.GetProducts)
			products.GET("/:id", handler.GetProduct)
			products.POST("", handler.CreateProduct)
			products.PUT("/:id", handler.UpdateProduct)
			products.DELETE("/:id", handler.DeleteProduct)
		}

		// 应用领域路由
		applications := api.Group("/applications")
		applications.Use(middleware.RequireAuth())
		{
			applications.GET("", handler.GetApplications)
			applications.GET("/:category", handler.GetApplicationByCategory)
			applications.POST("", handler.CreateApplication)
			applications.PUT("/:id", handler.UpdateApplication)
			applications.DELETE("/:id", handler.DeleteApplication)
		}

		// 新闻路由
		news := api.Group("/news")
		news.Use(middleware.RequireAuth())
		{
			news.GET("", handler.GetNews)
			news.GET("/:id", handler.GetNewsByID)
			news.POST("", handler.CreateNews)
			news.PUT("/:id", handler.UpdateNews)
			news.DELETE("/:id", handler.DeleteNews)
		}

		// 客户咨询路由
		contacts := api.Group("/contacts")
		contacts.Use(middleware.RequireAuth())
		{
			contacts.GET("", handler.GetContacts)
			contacts.DELETE("/:id", handler.DeleteContact)
		}

		// 统计数据路由
		stats := api.Group("/stats")
		stats.Use(middleware.RequireAuth())
		{
			stats.GET("/dashboard", handler.GetDashboardStats)
		}
	}

	// 提供静态文件服务
	r.Static("/static", "./static")

	// 启动服务器
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("Server starting on port %s", port)
	log.Fatal(r.Run(":" + port))
}
